using System;
using System.ServiceProcess;
using System.Configuration;
using System.Timers;
using System.Threading.Tasks;

namespace WebDavSyncTool
{
    public partial class WebDavSyncService : ServiceBase
    {
        private Timer syncTimer;
        private RCloneManager rcloneManager;

        public WebDavSyncService()
        {
            InitializeComponent();
            this.ServiceName = "WebDavSyncService";
        }

        // 添加公共方法用于控制台模式
        public void StartService()
        {
            OnStart(null);
        }

        public void StopService()
        {
            try
            {
                if (syncTimer != null)
                {
                    syncTimer.Stop();
                    syncTimer.Dispose();
                    syncTimer = null;
                }

                if (rcloneManager != null)
                {
                    rcloneManager.StopSync();  // 停止当前的同步进程
                    rcloneManager.Dispose();
                    rcloneManager = null;
                }

                Logger.LogInfo("同步服务已停止");
            }
            catch (Exception ex)
            {
                Logger.LogError("服务停止时发生错误", ex);
            }
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                // 重新加载配置文件
                ConfigurationManager.RefreshSection("appSettings");
                Logger.RefreshLogLevel();
                
                rcloneManager = new RCloneManager();
                
                // 从配置文件读取同步间隔，默认5分钟
                int interval;
                if (!int.TryParse(ConfigurationManager.AppSettings["SyncInterval"], out interval))
                {
                    interval = 300000; // 5分钟
                }

                Logger.LogInfo(string.Format("同步间隔设置为: {0}毫秒", interval));

                // 立即执行一次同步
                Logger.LogInfo("执行初始同步...");
                Task.Run(() => rcloneManager.SyncAsync()).Wait();

                syncTimer = new Timer();
                syncTimer.Interval = interval;
                syncTimer.Elapsed += OnTimer;
                syncTimer.Start();

                Logger.LogInfo("同步服务已启动");
            }
            catch (Exception ex)
            {
                Logger.LogError("服务启动失败", ex);
                throw;
            }
        }

        protected override void OnStop()
        {
            StopService();
        }

        private void OnTimer(object sender, ElapsedEventArgs args)
        {
            try
            {
                // 使用同步方式调用
                Task.Run(() => rcloneManager.SyncAsync()).Wait();
            }
            catch (Exception ex)
            {
                Logger.LogError("同步过程中发生错误", ex);
            }
        }
    }
} 